package com.ciwong.epaper.modules.me.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.adapter.AddBookAdapter;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.CatelogBean;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Node;
import com.ciwong.epaper.modules.epaper.bean.PackagesBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.CatalogNewActivity;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.LayersView;
import com.ciwong.epaper.modules.epaper.util.ScrollViewExtend;
import com.ciwong.epaper.modules.epaper.util.ViewPageTitle;
import com.ciwong.epaper.modules.me.bean.Coupon;
import com.ciwong.epaper.modules.me.bean.ExperimentService;
import com.ciwong.epaper.modules.me.bean.Photo;
import com.ciwong.epaper.modules.me.bean.Price;
import com.ciwong.epaper.modules.me.bean.SchoolDetail;
import com.ciwong.epaper.modules.me.bean.Service;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.bean.Trial;
import com.ciwong.epaper.modules.me.dao.MeAction;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.ui.mall.ItemServiceInfo;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.wordlist.util.SpaceItemDecoration;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DateUtils;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.PayHelper;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.widget.ListViewForScrollView;
import com.ciwong.epaper.widget.MyRecycleView;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpHelper;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.BuyMsg;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;
import com.ciwong.mobilepay.bean.PayDetail;
import com.ciwong.mobilepay.bean.SignParms;
import com.ciwong.mobilepay.bean.SignResult;
import com.ciwong.mobilepay.ui.EMainActivity;
import com.ciwong.mobilepay.util.PayUtil;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 购买服务界面
 */
public class BuyServiceActivity extends BaseActivity implements ItemServiceInfo.PriceBinder, NewBuyServicePriceAdapter.OnPriceClick,
        PullToRefreshView.OnFooterRefreshListener, PullToRefreshView.OnHeaderRefreshListener, ViewPageTitle.ViewPageChanag {


    /**
     * 获取服务状态详情类型：默认
     */
    private static final int GET_SERVICE_DETAIL_TYPE_DEFAULT = 0;

    /**
     * 获取服务状态详情类型：开通服务
     */
    private static final int GET_SERVICE_DETAIL_TYPE_OPEN = 1;

    /**
     * 获取服务状态详情类型：体验服务
     */
    private static final int GET_SERVICE_DETAIL_TYPE_EXPERIENCE = 2;

    /**
     * 习币支付签名KEY
     */
    private static final String PAY_SING_KEY = "17a4dgbcx3d58dca44788rtwc47cghfhd3csd8a6e29c31asd";

    /**
     * 服务ID
     */
    private int serviceId, sign;

    private String serviceNmae;

    private EApplication application;

    private ViewGroup buyServiceContainer;

    private ImageView buyServiceLogo;

    private TextView tv_buy_service_expire, buyServiceName,
            buyServicePeriod, buyServiceDesc, buyServiceSum;
    private ViewGroup servers_nums;
    /**
     * 底部购买栏，购买过且没到期就应该隐藏
     */
    private Button btn_buy_service;

    private int payResult = -1;

    private Handler handler = new Handler();

    private CWDialog mCWDialog;

    /**
     * 书籍列表
     */


    private int mSchoolId;
    private PullToRefreshView service_refresh_view;

    private ViewPageBookAdapter viewPageBookAdapter;


    private TextView net_work_error;
    private LinearLayout buyServiceNoData;
    private Service mService;
    private List<ServiceDetail> serviceDetailsforAddBookActivitys;//处理服务器同步购买书据较慢   这里做了延时刷新
    private float nowPrice = -1, OriginalPrice = -1;
    private int mounth = -1;

    private String tips = "";
    private static final int waitToResiltForBuy = 1;//处理服务器同步购买书据较慢   这里做了延时刷新

    //试用天数
    private int mTrialDay;
    private boolean isShiYong = false;


    private int bookPageCount = 1;


    //****************************************
    //书记详情页
    private ViewPageTitle page_titles;
    private LinearLayout ll_tab_text;
    private TextView tv_tittle;
    private List<String> pageTitles;
    private ViewPager viewpager_catalog;
    private int from;// 来源
    private int mBookId;
    private int salesType = -1;
    private CatelogBean catelogBean;
    private List<DownLoadInfo> mDownLoadInfos = new ArrayList<>();
    private List<CatalogueInfo> mCatalogueInfos = new ArrayList<>();
    private Map<DownLoadInfo, Hoder> downLoadInfoMap = new HashMap<DownLoadInfo, Hoder>();
    private int mSubjectId = -1;
    //错误提示信息
    private Object mesData;
    private LayoutInflater mInflater;
    private LayersView contentLayersView;
    private LinearLayout ll_coupon_text;
    private TextView tv_coupon_amount, tv_coupon_end_date, tv_total_amount;
    private Coupon mCoupon;
    //****************************************

    //增加同意协议
    private CheckBox check_agreement;
    private TextView tv_agreement, tv_agreement_child;
    private String packageName = "";

    private Handler mHander = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //处理服务器同步购买书据较慢   这里做了延时刷新
            switch (msg.what) {
                case waitToResiltForBuy:
                    if (mService != null && serviceDetailsforAddBookActivitys != null) {
                        if (requestCode == EpaperConstant.REQUEST_CODE_CLASS_JUMP_BUY_SERVICE_PAGE) {//来自资源中心
                            EpaperJumpManager.jumpToAddBookAndService(R.string.go_back, BuyServiceActivity.this, mService);
                            CWLog.d(TAG, "体验了！！！！requestCode");
                            finish();
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra(IntentFlag.INTENT_FLAG_OBJ, mService);
                            intent.putExtra(IntentFlag.INTENT_FLAG_PAY, 0);
                            //购买回调服务列表
                            intent.putExtra(IntentFlag.INTENT_FLAG_OBJ_LIST, (Serializable) serviceDetailsforAddBookActivitys);
                            setResult(RESULT_OK, intent);
                            CWLog.d(TAG, "体验了！！！！");
                            finish();
                        }
                    }
                    break;

            }
            return false;
        }
    });

    /**
     * 无权限提示
     */
    private String str_tips;
    private TextView tv_tips;
    private MyRecycleView nllv_price_list;
    //private HorizontalScrollView price_scoll;
    /**
     * 免费体验选项
     */

    private ImageView iv_service_down;

    private TextView tv_buy_count;
    private LinearLayout ll_buy_service;
    private CatalogueInfo mCurrentCatalogueInfo;
    private Hoder mCurrentHolder;
    private DownLoadInfo mCurrentDownloadInfo;
    private DownLoadInfo mCurrentClickDownloadInfo;
    private EpaperInfo mCurrentEpaperInfo;
    private int requestCode;
    private boolean isTheLastPageShow = false;


    @Override
    protected void preCreate() {
        Intent intent = getIntent();
        if (intent != null) {
            sign = intent.getIntExtra(IntentFlag.INTENT_FLAG_SIGN, -1);
            serviceId = intent.getIntExtra(IntentFlag.INTENT_FLAG_ID, 0);
            requestCode = intent.getIntExtra(IntentFlag.INTENT_FLAG_REQUESTCODE, 0);
            str_tips = intent.getStringExtra(IntentFlag.INTENT_FLAG_TIP);
            from = IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE;
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_buy_service;
    }

    /**
     * 服务下架文字提示
     */
    TextView tv_server_Expired, tv_service_down_data, tv_service_down;
    ScrollViewExtend sll_scroll;

    @Override
    protected void findViews() {

        tv_server_Expired = findViewById(R.id.tv_server_Expired);
        tv_service_down = findViewById(R.id.tv_service_down);
        tv_service_down_data = findViewById(R.id.tv_service_down_data);

        buyServiceContainer = findViewById(R.id.buy_service_container);
        tv_buy_service_expire = findViewById(R.id.tv_buy_service_expire);
        buyServiceLogo = findViewById(R.id.buy_service_logo);
        buyServiceName = findViewById(R.id.buy_service_name);
        buyServicePeriod = findViewById(R.id.buy_service_period);
        buyServiceDesc = findViewById(R.id.buy_service_desc);

        buyServiceNoData = findViewById(R.id.buy_service_no_data);
        net_work_error = findViewById(R.id.net_work_error);
        btn_buy_service = findViewById(R.id.btn_buy_service);
        service_refresh_view = findViewById(R.id.service_refresh_view);

        tv_tips = findViewById(R.id.tv_tips);
        nllv_price_list = findViewById(R.id.nllv_price_list);
        nllv_price_list.setLayoutManager(new LinearLayoutManager(BuyServiceActivity.this, LinearLayoutManager.VERTICAL, false));
        nllv_price_list.addItemDecoration(new SpaceItemDecoration(15));
        // price_scoll=findViewById(R.id.price_scoll);


        sll_scroll = findViewById(R.id.sll_scroll);
        tv_buy_count = findViewById(R.id.tv_buy_count);
        ll_buy_service = findViewById(R.id.ll_buy_service);
        iv_service_down = findViewById(R.id.iv_service_down);


        page_titles = findViewById(R.id.page_titles);
        ll_tab_text = findViewById(R.id.ll_tab_text);
        tv_tittle = findViewById(R.id.tv_tittle);
        viewpager_catalog = findViewById(R.id.viewpager_catalog);

        ll_coupon_text = findViewById(R.id.ll_coupon_text);
        tv_coupon_amount = findViewById(R.id.tv_coupon_amount);
        tv_coupon_end_date = findViewById(R.id.tv_coupon_end_date);
        tv_total_amount = findViewById(R.id.tv_total_amount);
        check_agreement = findViewById(R.id.check_agreement);
        tv_agreement = findViewById(R.id.tv_agreement);
        tv_agreement_child = findViewById(R.id.tv_agreement_child);
        packageName = getPackageName();
    }

    @Override
    protected void initEvent() {
        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                int status = mCurrentDownloadInfo.getStatus();
                if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                    DownLoad.getInstance().pauseTask(mCurrentDownloadInfo);
                }

            }
        });
        try {
            btn_buy_service.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!check_agreement.isChecked()) {
                        ToastUtil.INSTANCE.toastCenterError(R.string.buy_agreement_secret_tips);
                    } else if (EConstants.IS_YOUKE) {
                        NewLoginDialog newLoginDialog = new NewLoginDialog(BuyServiceActivity.this);
                        newLoginDialog.showLoginDialog();
                    } else {

                        if (null != mService && mService.getSign() == 3) {
                            //免费服务
                            if (NetworkUtils.isOnline()) {
                                getSignServerOrder("1", mService);
                            } else {
                                ToastUtil.INSTANCE.toastCenterNoNetError();
                            }
                        } else if (btn_buy_service.getText().toString().equals("免费体验")) {
                            //免费体验
                            if (NetworkUtils.isOnline()) {
                                experiment(mService);
                            } else {
                                ToastUtil.INSTANCE.toastCenterNoNetError();
                            }
                        } else if (btn_buy_service.getText().toString().equals("通知家长购买")) {
                            //通知家长购买
                            if (NetworkUtils.isOnline()) {
                                sendBuyService();
                            } else {
                                ToastUtil.INSTANCE.toastCenterNoNetError();
                            }
                        } else {
                            if (null != mService && nowPrice != -1 && OriginalPrice != -1 && mounth != -1) {
                                int remain = DateUtils.getIntervalCount2(new Date(), DateUtils.String2Date(DateUtils.DATE_LONG, serviceDetail.getExpireTime()));
                                if (serviceDetail != null && remain >= 1) {
                                    //剩余使用时间大于1天
                                    if (serviceDetail.isBuy()) {
                                        //购买过的。
                                        if (null != mCWDialog && mCWDialog.isShowing()) {
                                            mCWDialog.dismiss();
                                        }
                                        mCWDialog = new CWDialog(BuyServiceActivity.this);
                                        if (salesType == 1) {
                                            mCWDialog.setMessage("书籍还有" + remain + "天到期，是否确认购买？");
                                        } else {
                                            mCWDialog.setMessage("服务还有" + remain + "天到期，是否确认购买？");
                                        }

                                        mCWDialog.setCancelable(false);
                                        mCWDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });
                                        mCWDialog.setPositiveButton("确定",
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
//                                                openService(mService, nowPrice, OriginalPrice, mounth);

                                                        openService(mService, nowPrice, OriginalPrice, mounth);
                                                        dialog.dismiss();
                                                    }
                                                })
                                                .show();
                                    } else {
                                        //免费体验的直接跳转，不弹窗
                                        openService(mService, nowPrice, OriginalPrice, mounth);
                                    }
                                } else {
                                    openService(mService, nowPrice, OriginalPrice, mounth);
                                }
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.getStackTrace();
        }

        tv_agreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用协议
                MeJumpManager.jumpAgreementActivity(R.string.go_back, BuyServiceActivity.this, getString(R.string.agreement_payment_url), getString(R.string.agreement_payment), AgreementActivity.LOGIN_ACTION);
            }
        });
        tv_agreement_child.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用协议
                MeJumpManager.jumpAgreementActivity(R.string.go_back, BuyServiceActivity.this, getString(R.string.agreement_payment_url), getString(R.string.agreement_payment), AgreementActivity.LOGIN_ACTION);
            }
        });
        //是否同意隐私协议
        boolean privacyAgreement = false;
        try {
            privacyAgreement = CWSys.getSharedBoolean("buyPrivacyAgreement" + packageName + getPackageManager()
                    .getPackageInfo(getPackageName(), 0).versionName, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (privacyAgreement) {
            check_agreement.setChecked(true);
        }
        check_agreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                try {
                    if (isChecked) {
                        CWSys.setSharedBoolean("buyPrivacyAgreement" + packageName + getPackageManager()
                                .getPackageInfo(getPackageName(), 0).versionName, true);
                    } else {
                        CWSys.setSharedBoolean("buyPrivacyAgreement" + packageName + getPackageManager()
                                .getPackageInfo(getPackageName(), 0).versionName, false);
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //获取订单 接口   也是免费服务获取接口
    public void getSignServerOrder(String rechargeType, final Service mService) {
        try {
            //服务购买
            PayDetail payDetail = PayHelper.getInstance().getPayDetail(getUserInfoBase().getUserId(), getUserInfoBase().getRealName(), mService.getName(), mService.getLogo(),
                    OriginalPrice, mService.getDesc(), mounth, 1, "", "", mService.getId() + "", "0", "1", "2", "", "", mService.getId() + "", null);
            final SignParms signparms = payDetail.getSingParms();
            if (signparms == null) {
                CWLog.d("debug", "getSignServerOrder签名参数为空:");
            } else {
                HashMap params = new HashMap();
                params.put(HttpRequest.REQUEST_MODULES, MeAction.class.getName());
                params.put(HttpRequest.REQUEST_ACTION, MeAction.ACTION_REF_PLAY_GET_ORDER);
                params.put("brandId", String.valueOf(signparms.getBrandId()));
                params.put("serviceId", signparms.getServiceId());
                params.put("userId", String.valueOf(signparms.getUserId()));
                params.put("userName", signparms.getUserName());
                params.put("total_fee", PayUtil.radixPoint(signparms.getTotal_fee(), 2));
                params.put("goods_num", String.valueOf(signparms.getGoods_num()));
                params.put("rechargeType", rechargeType);
                HttpRequest request = new HttpRequest(params, new Response.ErrorListener() {
                    public void onErrorResponse(VolleyError arg0) {
                        CWLog.d("debug", arg0.toString() + "getSignServerOrder获取订单签名出错 onErrorResponse!");
                        ToastUtil.INSTANCE.toastCenterError("获取失败");
                    }
                }, new BaseRequest.ResponseCallback() {
                    public void success(Object obj, int resultCode, int errorCode, String msg) {
                        CWLog.e("debug", String.valueOf(obj));
                        if (resultCode == 0 && errorCode == 0) {
                            SignResult signresult = (SignResult) obj;
                            if (signresult.isFlag()) {
                                if ("".equals(signresult.getBugmsg())) {
                                    refreshServiceStateAction(GET_SERVICE_DETAIL_TYPE_DEFAULT);
                                    CWLog.d("debug", "getSignServerOrder成功结果:msg:=0元购买 ");
                                    ToastUtil.INSTANCE.toastCenterSuccess("获取成功");
                                    //通知刷新自主学习
                                    sendBroadcast(new Intent(EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK));
                                    //开通后要回到书柜
                                    Intent intent = new Intent();
                                    intent.putExtra(IntentFlag.INTENT_FLAG_OBJ, mService);
                                    intent.putExtra(IntentFlag.INTENT_FLAG_PAY, 0);
                                    setResult(RESULT_OK, intent);
                                    //在MainActivity中回调中会跳到书柜页面中
                                    mHander.sendEmptyMessageDelayed(waitToResiltForBuy, 2000);
                                }
                            } else {
                                CWLog.d("debug", "getSignServerOrder获取签名失败 ");
                                ToastUtil.INSTANCE.toastCenterError("获取失败");
                            }
                        } else {
                            CWLog.d("debug", "getSignServerOrder获取签名失败 ");
                            ToastUtil.INSTANCE.toastCenterError("获取失败");
                        }
                    }

                    public void error(int errorCode, String msg) {
                        CWLog.d("debug", "getSignServerOrder获取签名失败 error:" + errorCode + "msg=" + msg);
                        ToastUtil.INSTANCE.toastCenterError("获取失败");
                    }
                });
                request.setResponseDataType(2);
                request.setResponseClazz(SignResult.class);
                Volley.newRequestQueue(this.getApplicationContext()).add(request);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    @Override
    protected void init() {
        try {
            application = (EApplication) getApplication();
            mInflater = LayoutInflater.from(this);
            setServiceDetail();

            if (BaseApplication.PLATFORM_PAD != BaseApplication.PLATFORM_ENV) {

                setImgRightBtn(R.mipmap.nav_right_phone);
                setImgRightBtnListener(new ViewOnClickListener() {
                    @Override
                    public void avertRepeatOnClick(View v) {
                        contactService();
                    }
                });
            }
            setGoBackListener(new GoBackListener() {
                @Override
                public void goBack() {
                    Intent intent = new Intent();
                    intent.putExtra(IntentFlag.INTENT_FLAG_PAY, payResult);
                    if (payResult >= 0) {
                        setResult(RESULT_OK, intent);
                    } else {
                        setResult(RESULT_CANCELED, intent);
                    }
                    finish();
                }
            });
            service_refresh_view.setOnFooterRefreshListener(this);
            service_refresh_view.setOnHeaderRefreshListener(this);

            if (TextUtils.isEmpty(str_tips)) {
                tv_buy_service_expire.setVisibility(View.VISIBLE);
                tv_tips.setText("");
                tv_tips.setVisibility(View.GONE);
            } else {
                tv_buy_service_expire.setVisibility(View.GONE);
                tv_tips.setVisibility(View.VISIBLE);
                tv_tips.setText(str_tips);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    @Override
    protected void loadData() {


        try {
            if (!NetworkUtils.isOnline()) {
                buyServiceContainer.setVisibility(View.GONE);
                net_work_error.setVisibility(View.VISIBLE);
                return;
            }

            MeDao.getInstance().getServices(EApplication.BRAND_ID, serviceId,
                    new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            if (errorCode != 10004 && errorCode != 27 && errorCode != 17) {
                                DialogUtil.showFailedToastByErrorType(BuyServiceActivity.this, data);
                            }
                            hideMiddleProgressBar();
                            hidenLoadingView();
                        }

                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            DialogUtil.showFailedToastByErrorType(BuyServiceActivity.this, data);
                            hideMiddleProgressBar();
                            hidenLoadingView();
                        }

                        @Override
                        public void success(Object data) {
                            hidenLoadingView();
                            List<Service> services = (List<Service>) data;
                            Service service = new Service();
                            service.setId(serviceId);
                            if (services != null && !services.isEmpty()) {
                                int indexOf = services.indexOf(service);
                                if (indexOf >= 0) {
                                    mService = services.get(indexOf);
                                }
                            }
                            if (mService != null) {

                                sign = mService.getSign();

                                salesType = mService.getSalesType();
                                setServiceDetail();
                                if (salesType == 1) {
                                    mBookId = mService.getBookId();
                                    getLocData();//获取书籍相关的信息
                                    ViewGroup.LayoutParams params = buyServiceLogo.getLayoutParams();
                                    params.width = ViewUtil.dip2px(BuyServiceActivity.this, 75);
                                    buyServiceLogo.setLayoutParams(params);

                                } else if (salesType == 0) {
                                    //加载服务相关的信息
//                                    getServiceBook();
                                    //补丁包新逻辑
                                }
                                getServiceBook();

                                serviceId = mService.getId();
                                serviceNmae = mService.getName();
                                if (salesType == 1) {
                                    setTitleText("书籍详情");
                                } else {
                                    setTitleText("服务详情");
                                }
                                if (mService.getOrderbase() <= 0) {
                                    tv_buy_count.setVisibility(View.GONE);
                                } else {
                                    tv_buy_count.setVisibility(View.VISIBLE);
                                    tv_buy_count.setText("(已有" + mService.getBuycount() + "人购买)");
                                }

                                String logoUrl = mService.getLogo();
                                ImageLoader.getInstance().displayImage(
                                        TextUtils.isEmpty(logoUrl)
                                                ? "drawable://"
                                                + R.mipmap.ic_launcher
                                                : logoUrl,
                                        buyServiceLogo,
                                        EConstants.getDefAvatarCircleBuilder());
                                buyServiceName.setText(mService.getName());
                                if (salesType == 1) {
                                    if (mService.getGradeName() != null && !"".equals(mService.getGradeName())) {
                                        buyServicePeriod.setText(
                                                getString(R.string.buy_service_period,
                                                        mService.getGradeName()));
                                        buyServicePeriod.setVisibility(View.VISIBLE);
                                    }

                                } else {
                                    //适用学段为空的时候隐藏
                                    if (mService.getPeriod() != null && !"".equals(mService.getPeriod())) {
                                        buyServicePeriod.setText(
                                                getString(R.string.buy_service_period,
                                                        mService.getPeriod()));
                                        buyServicePeriod.setVisibility(View.VISIBLE);
                                    } else {
                                        buyServicePeriod.setVisibility(View.GONE);
                                    }
                                }
                                //描述为空的时候隐藏
                                if (mService.getDesc() != null && !"".equals(mService.getDesc())) {
                                    buyServiceDesc.setText(
                                            getString(R.string.buy_service_desc,
                                                    mService.getDesc()));
                                    buyServiceDesc.setVisibility(View.VISIBLE);
                                } else {
                                    buyServiceDesc.setVisibility(View.GONE);
                                }


                                if (mService.getTrial() != null) {
                                    List<Trial> trialList = mService.getTrial();

                                    if (trialList != null) {
                                        Trial trial = null;
                                        for (Trial tempTrial : trialList) {
                                            if (tempTrial.getTrlaltypeId() == EpaperConstant.TRLALTYPEID_OF_MOBILE) {
                                                trial = tempTrial;
                                                break;
                                            }
                                        }
                                        // price_scoll.addView(new NewPriceView(BuyServiceActivity.this,mService.getPrice(), mService,trial));
                                        NewBuyServicePriceAdapter newBuyServicePriceAdapter = new NewBuyServicePriceAdapter(BuyServiceActivity.this, mService.getPrice(), mService, trial);
                                        //final BuyServicePriceAdapter buyServicePriceAdapter = new BuyServicePriceAdapter(mService.getPrice(), mService);
                                        newBuyServicePriceAdapter.setOnPriceClick(BuyServiceActivity.this);
                                        nllv_price_list.setAdapter(newBuyServicePriceAdapter);
                                        ll_coupon_text.setVisibility(View.VISIBLE);
                                        if (null != trial && trial.getTrlalcount() == 0 && trial.getTrlalsum() > 0 && mService.getSign() != 3) {
                                            //显示免费体验按钮
                                            mTrialDay = trial.getTrlalsum();
                                            btn_buy_service.setText("免费体验");
                                            ll_coupon_text.setVisibility(View.GONE);
                                        } else {
                                            //隐藏免费体验按钮
                                            // ll_free_price_item.setVisibility(View.GONE);
                                            if (mService.getSign() == 3) {
                                                btn_buy_service.setText("免费获取");
                                                tv_buy_count.setText("(已有" + mService.getBuycount() + "人获取)");
                                                ll_coupon_text.setVisibility(View.GONE);
                                            } else {
                                                if (mService.getBuyServiceType() == 1) {
                                                    if (mService.getPrice().size() > 0) {
                                                        nowPrice = mService.getPrice().get(0).getPrice();
                                                        btn_buy_service.setText("通知家长购买" + "(" + nowPrice + "元)");
                                                    } else {
                                                        btn_buy_service.setText("通知家长购买");
                                                    }
                                                    ll_coupon_text.setVisibility(View.VISIBLE);
                                                } else {
                                                    if (mService.getPrice().size() > 0) {
                                                        nowPrice = mService.getPrice().get(0).getPrice();
                                                        java.text.DecimalFormat df = new java.text.DecimalFormat("#0");
                                                        btn_buy_service.setText("立即购买" + "(" + df.format(nowPrice) + "元)");
                                                    } else {
                                                        btn_buy_service.setText("立即购买");
                                                    }
                                                    ll_coupon_text.setVisibility(View.VISIBLE);
                                                }
                                            }
                                            //默认选中第一个价格
                                            if (mService.getPrice().size() > 0) {
                                                nowPrice = mService.getPrice().get(0).getPrice();
                                                OriginalPrice = mService.getPrice().get(0).getPrice();
                                                mounth = mService.getPrice().get(0).getUnit();
                                                tips = mService.getPrice().get(0).getTips();
                                                if (mService.getCouponList() != null && mService.getCouponList().size() > 0) {
                                                    ll_coupon_text.setVisibility(View.VISIBLE);
                                                    btn_buy_service.setText("立即购买");
                                                    setCouponPrice(nowPrice, mService.getCouponList());
                                                } else {
                                                    ll_coupon_text.setVisibility(View.GONE);
                                                }
                                            } else {
                                                ll_coupon_text.setVisibility(View.GONE);
                                            }
                                        }
                                    }
                                }
                                refreshServiceStateAction(GET_SERVICE_DETAIL_TYPE_DEFAULT);


                            } else {
                                if (salesType == 1) {
                                    setTitleText(R.string.server_book_out);
                                    tv_service_down.setText(R.string.server_book_out);
                                } else {
                                    setTitleText(R.string.server_out);
                                }

                                tv_server_Expired.setVisibility(View.VISIBLE);


                                if (serviceDetail.isbExpired()) {
                                    tv_server_Expired.setVisibility(View.GONE);
                                }
                                buyServiceNoData.setVisibility(View.VISIBLE);
                                buyServiceContainer.setVisibility(View.GONE);
                                hideMiddleProgressBar();
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case RequestCode.BuyServiceActivityResquestCode.REQ_CODE_PAY:
                    payResult = data.getIntExtra(EMainActivity.PAY_RESULT, 0);
                    // 支付购买成功
                    if (payResult == EMainActivity.PAY_RESULT_SUCCES) {
                        MeDao.getInstance().getUserPoint();
                        showToastSuccess(R.string.buy_server_succ_hint);
                        refreshServiceStateAction(GET_SERVICE_DETAIL_TYPE_OPEN);
                    } else {
                        showToastError(R.string.buy_server_err_hint);
                    }
                    break;
                default:
                    break;
            }
        }
        hideMiddleProgressBar();
    }


    //
    private List<EpaperInfo> epaperInfos = new ArrayList<EpaperInfo>();
    private AddBookAdapter addBookAdapter;
    private RecyclerView recyclerViewContent;
    private BookContentAdapter bookContentAdapter;
    private int books_nums = 0;

    /**
     * 获取书籍列表
     *
     * @param schoolId 学校ID
     */
    private void getServiceBooks(final int schoolId) {
        EpaperDao.getInstance().getServiceBooks(schoolId, serviceId, bookPageCount,
                EConstants.MAX_REQUEST_BOOK_COUNT, new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        loadOver();
                    }

                    @Override
                    public void failed(Object data) {
                        super.failed(data);
                        loadOver();
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            BasePaging<EpaperInfo> epaperInfoBasePaging = (BasePaging<EpaperInfo>) data;
                            if (epaperInfoBasePaging.getPageList().size() > 0) {
                                if (bookPageCount == 1) {
                                    epaperInfos.clear();
                                }
                                epaperInfos.addAll(epaperInfoBasePaging.getPageList());
//                                addBookAdapter.notifyDataSetChanged();
                                books_nums = epaperInfoBasePaging.getTotalCount();
                            }
//                        if (epaperInfos.size() == EConstants.MAX_REQUEST_BOOK_COUNT) {
//                            getServiceBooks(mSchoolId);
//                        }
                            if (epaperInfos != null) {
                                //新接口没有服务名称信息　需要在这里添加　
                                for (EpaperInfo epaperInfo : epaperInfos
                                ) {
                                    EpaperInfo.Server server = new EpaperInfo.Server();
                                    if (mService != null) {
                                        server.setName(mService.getName());
                                    }
                                    epaperInfo.setServer(server);
                                }
                            }

                            initViewPage(salesType);


                            if (epaperInfos != null && epaperInfoBasePaging != null && epaperInfos.size() >= epaperInfoBasePaging.getTotalCount()) {
                                isTheLastPageShow = true;
                            } else {
                                isTheLastPageShow = false;
                            }

                            loadOver();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }


                    }
                });
    }

    ServiceDetail serviceDetail;
    List<ServiceDetail> serviceDetails;

    /**
     * 设置服务详情
     * 状态有未购买，已经购买但过期，购买了没过期小于30天，购买没过期大于30天，试用期当中
     */
    private void setServiceDetail() {
        try {
            serviceDetails = application.getServiceDetails();
            if (serviceDetails == null) {
                UserInfoBase userInfoBase = application.getUserInfoBase();
                if (null != userInfoBase) {
                    MeDao.getInstance().getServiceDetails(application,
                            EApplication.BRAND_ID, userInfoBase.getUserId(), 0,
                            new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                                @Override
                                public void failed(int errorCode, Object data) {
                                    super.failed(errorCode, data);
                                    hideMiddleProgressBar();
                                }

                                @Override
                                public void failed(Object data) {
                                    super.failed(data);
                                    hideMiddleProgressBar();
                                }

                                @Override
                                public void success(Object data) {
                                    serviceDetails = (List<ServiceDetail>) data;
                                    setServiceState();
                                    SerializableManager.getInstance().serialize(
                                            SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST,
                                            (Serializable) serviceDetails);
                                    application.setServiceDetails(serviceDetails);
                                    hideMiddleProgressBar();
                                }

                            });
                }
            } else {
                setServiceState();
            }
        } catch (Exception e) {
            e.getStackTrace();
        }


    }


    private void setServiceState() {


        try {
            serviceDetail = new ServiceDetail();
            serviceDetail.setServiceType(serviceId);
            serviceDetail.setbExpired(true);
            serviceDetail.setIsShow(1);
            serviceDetail.setSign(sign);
            int indexOf = -1;
            if (serviceDetails != null) {
                //不存在就返回-1
                indexOf = serviceDetails.indexOf(serviceDetail);
                if (indexOf >= 0) {
                    serviceDetail = serviceDetails.get(indexOf);
                }
            }

            setTitleText(serviceDetail.getServiceTypeName());
            String serviceMessage = "服务已于";

            //服务状态决定 购买栏显示与否,1没购买，没试用，显示底部购买栏，2：到期时间小于31 天或者试用中显示底部购买栏
            // 购买栏里面的试用按钮由另外服务信息接口决定

            //四种状态
            //未购买  未获取

            if (indexOf < 0) {

                if (serviceDetail.getSign() == 3) {//免费服务  0元购买 显示的未获取
                    ll_buy_service.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(str_tips)) {
                        tv_buy_service_expire.setText("未获取");
                        tv_buy_service_expire.setVisibility(View.VISIBLE);
                    } else {
                        tv_buy_service_expire.setVisibility(View.GONE);
                    }

                    btn_buy_service.setText("免费获取");

                } else {
                    //没购买，没试用 正常价格
                    ll_buy_service.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(str_tips)) {
                        if (TextUtils.isEmpty(str_tips)) {
                            tv_buy_service_expire.setText("未购买");
                            tv_buy_service_expire.setVisibility(View.VISIBLE);
                        } else {
                            tv_buy_service_expire.setVisibility(View.GONE);
                        }

                    } else {
                        tv_buy_service_expire.setVisibility(View.GONE);
                    }

                }

            } else {
                String expireTime = serviceDetail.getExpireTime();

                if (null != expireTime && expireTime.indexOf("T") != -1) {
                    expireTime = expireTime.replace('T', ' ');
                }
                expireTime = DateUtils.String2typeStr(expireTime, DateUtils.DATE_LONG, DateUtils.DATE_SHORT0);

                if (serviceDetail.getSign() == 3) {//免费服务  0元购买 显示的未获取
                    ll_buy_service.setVisibility(View.GONE);
                    if (TextUtils.isEmpty(str_tips)) {
                        tv_buy_service_expire.setText("已获取");
                        tv_buy_service_expire.setVisibility(View.VISIBLE);
                    } else {
                        tv_buy_service_expire.setVisibility(View.GONE);
                    }
                    String html = getString(R.string.server_no_show_3, expireTime);

                    tv_server_Expired.setText(html);

                } else {


//                boolean enough = isEnoughTime(expireTime);

                    /**
                     * 不显示情况
                     * 1：买断 模式且已经购买了
                     * 2：免费且已经免费获取过了
                     */

                    if ((serviceDetail.getSign() == 1 && serviceDetail.isBuy()) || serviceDetail.getSign() == 3) {
                        ll_buy_service.setVisibility(View.GONE);
                    } else {
                        ll_buy_service.setVisibility(View.VISIBLE);
                    }


                    //expireTime = DateUtils.String2typeStr(expireTime, DateUtils.DATE_LONG, DateUtils.DATE_SHORT0);
                    if (indexOf >= 0 && serviceDetail.isbExpired()) {
                        //购买了已经过期了
                        if (TextUtils.isEmpty(str_tips)) {
                            if (salesType == 1) {
                                tv_buy_service_expire.setText("书籍已于" + expireTime + "过期");
                            } else {
                                tv_buy_service_expire.setText(serviceMessage + expireTime + "过期");
                            }

                            tv_buy_service_expire.setVisibility(View.VISIBLE);
                        } else {
                            tv_buy_service_expire.setVisibility(View.GONE);
                        }
                        String html = getString(R.string.server_no_show_3, expireTime);

                        tv_server_Expired.setText(html);

                    } else if (indexOf >= 0 && !serviceDetail.isbExpired() && serviceDetail.isBuy()) {
                        //购买了没有过期
                        if (serviceDetail.getSign() == 1 && serviceDetail.getIsFree() == 0) {//买断且不是赠送
                            if (TextUtils.isEmpty(str_tips)) {
                                tv_buy_service_expire.setText("已购买(永久使用)");
                                tv_buy_service_expire.setVisibility(View.VISIBLE);
                            } else {
                                tv_buy_service_expire.setVisibility(View.GONE);
                            }
                        } else if (serviceDetail.getSign() == 0 || serviceDetail.getIsFree() == 1) {//按月购买  或者赠送
                            if (TextUtils.isEmpty(str_tips)) {
                                tv_buy_service_expire.setText("已购买(" + expireTime + "到期)");
                                tv_buy_service_expire.setVisibility(View.VISIBLE);
                            } else {
                                tv_buy_service_expire.setVisibility(View.GONE);
                            }

                        }
                        String html = getString(R.string.server_no_show_3, expireTime);

                        tv_server_Expired.setText(html);
                        iv_service_down.setImageResource(R.mipmap.icon_service_down_noexpire);
                    } else if (indexOf >= 0 && !serviceDetail.isbExpired() && !serviceDetail.isBuy()) {
                        //没购买，试用没有过期
                        if (TextUtils.isEmpty(str_tips)) {
                            tv_buy_service_expire.setText("试用中(" + expireTime + "到期)");
                            tv_buy_service_expire.setVisibility(View.VISIBLE);
                        } else {
                            tv_buy_service_expire.setVisibility(View.GONE);
                        }
                        iv_service_down.setImageResource(R.mipmap.icon_service_down_noexpire);
                        String html = getString(R.string.server_no_show_3, expireTime);
                        tv_server_Expired.setText(html);
                        isShiYong = true;
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }


    }


    private void getServiceBook() {

        SchoolDetail schoolDetail = application.getSchoolDetail();
        final int schoolId = schoolDetail == null ? 0
                : schoolDetail.getSchoolId();
        mSchoolId = schoolId;
        getServiceBooks(schoolId);
        String key = SerializableManager.SerializeKey.SHARE_KEY_NEWSPAPER_LIST
                + "_" + serviceId;


    }

    /**
     * 刷新服务状态
     *
     * @param type 获取服务状态详情类型
     */
    private void refreshServiceStateAction(final int type) {
        try {
            showMiddleProgressBar(getTitleText());
            MeDao.getInstance().getServiceDetails(application,
                    EApplication.BRAND_ID, getUserInfoBase().getUserId(), 0,
                    new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            hideMiddleProgressBar();
                            showToastError(errorCode, data);
                        }

                        @Override
                        public void success(Object data) {
                            serviceDetailsforAddBookActivitys = (List<ServiceDetail>) data;
                            hideMiddleProgressBar();
                            switch (type) {
                                case GET_SERVICE_DETAIL_TYPE_OPEN:
                                    mHander.sendEmptyMessageDelayed(waitToResiltForBuy, 2000);
                                    //通知刷新自主学习
                                    sendBroadcast(new Intent(EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK));
                                    break;

                                case GET_SERVICE_DETAIL_TYPE_EXPERIENCE:
//                                buyServiceExperiment.setEnabled(true);
//                                buyServiceExperiment.setVisibility(View.GONE);
                                    if (salesType == 1) {
                                        ToastUtil.INSTANCE.toastCenter(BuyServiceActivity.this, "获取成功! 您可以享受" + mTrialDay + "天免费体验", R.mipmap.ic_success);

                                    } else {
                                        ToastUtil.INSTANCE.toastCenter(BuyServiceActivity.this, "获取成功! 您可以享受" + mTrialDay + "天免费体验", R.mipmap.ic_success);
                                    }
                                    //通知刷新自主学习
                                    sendBroadcast(new Intent(EpaperConstant.BROADCAST_GET_SERVICE_REFRESH_BOOK_DESK));

                                    jumpToSuss();

                                    break;

                                default:
                                    setResult(RESULT_OK);
                                    break;
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    /**
     * 开通免费体验
     *
     * @param service 服务信息
     */
    private void experiment(final Service service) {
        try {
            showMiddleProgressBar(getTitleText());
            UserInfoBase userInfoBase = application.getUserInfoBase();
            MeDao.getInstance().openExperiment(
                    userInfoBase == null ? 0 : userInfoBase.getUserId(),
                    service == null ? 0 : service.getId(),
                    ServiceDetail.VersionType.VERSION_TYPE_PERSONAL, 14,
                    new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            if (errorCode != 10004 && errorCode != 27 && errorCode != 17) {
                                DialogUtil.showFailedToastByErrorType(BuyServiceActivity.this, data);
                            }
                            hideMiddleProgressBar();
//                        buyServiceExperiment.setEnabled(true);
                        }

                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            DialogUtil.showFailedToastByErrorType(BuyServiceActivity.this, data);
                            hideMiddleProgressBar();
//                        buyServiceExperiment.setEnabled(true);
                        }

                        @Override
                        public void success(Object data) {
                            ExperimentService experimentService = (ExperimentService) data;

                            if (experimentService.isResult()) {
                                refreshServiceStateAction(GET_SERVICE_DETAIL_TYPE_EXPERIENCE);
                            } else {
                                //showToastError(R.string.experiment_error);
                                hideMiddleProgressBar();
//                            buyServiceExperiment.setEnabled(true);
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 判断是否有家长绑定
     */
    private void getMyParent() {
        try {
            showMiddleProgressBar(getTitleText());
            UserInfoBase userInfoBase = application.getUserInfoBase();
            MeDao.getInstance().getMyParent(
                    userInfoBase == null ? 0 : userInfoBase.getUserId(),
                    new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            if (errorCode != 10004 && errorCode != 27 && errorCode != 17) {
                                DialogUtil.showFailedToastByErrorType(BuyServiceActivity.this, data);
                            }
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void failed(Object data) {
                            super.failed(data);
                            hideMiddleProgressBar();
                            //跳转绑定界面
                        }

                        @Override
                        public void success(Object data) {
                            hideMiddleProgressBar();
                            //调用发送消息接口
                            sendBuyService();
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 通知家长购买
     */
    private void sendBuyService() {
        try {
            showMiddleProgressBar(getTitleText());
            UserInfoBase userInfoBase = application.getUserInfoBase();
            MeDao.getInstance().sendBuyService(
                    userInfoBase == null ? 0 : userInfoBase.getUserId(), serviceId, serviceNmae, nowPrice, mounth,
                    new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            if (errorCode == 10010) {
                                //没有绑定家长，跳转客服界面
                                MeJumpManager.jumpSendParentBuyActivity(BuyServiceActivity.this, R.string.go_back);
                            } else {
                                if (errorCode != 10004 && errorCode != 27 && errorCode != 17) {
                                    DialogUtil.showFailedToastByErrorType(BuyServiceActivity.this, data);
                                }
                            }
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void success(Object data) {
                            hideMiddleProgressBar();
                            //通知成功
                            ToastUtil.INSTANCE.toastCenter(BuyServiceActivity.this, "订单已推送到习习向上公众号", Toast.LENGTH_LONG, -1);
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private void jumpToSuss() {
        //开通后要回到书柜
        mHander.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (requestCode == EpaperConstant.REQUEST_CODE_CLASS_JUMP_BUY_SERVICE_PAGE) {//来自资源中心
                    EpaperJumpManager.jumpToAddBookAndService(R.string.go_back, BuyServiceActivity.this, mService);
                    CWLog.d(TAG, "体验了！！！！postDelayed requestCode");
                    finish();
                } else {
                    Intent intent = new Intent();
                    intent.putExtra(IntentFlag.INTENT_FLAG_OBJ, mService);
                    intent.putExtra(IntentFlag.INTENT_FLAG_PAY, 0);
                    CWLog.d(TAG, "体验了！！！！postDelayed");
                    finish();
                }
            }
        }, 1500);

    }


    /**
     * 开通服务
     *
     * @param
     */
    private void openService(Service service, float nowPrice, float OriginalPrice, int mounth) {
        UserInfoBase userInfo = getUserInfoBase();
        String notifyUrl = concatOpenVIPPayNotifyUrl(userInfo.getUserId() + "",
                mService.getId(), 1, nowPrice, OriginalPrice, mounth);
        CWLog.e("notifyUrl=", notifyUrl);
        setValideSource(false);
        //服务购买
        PayDetail payDetail = PayHelper.getInstance().getPayDetail(userInfo.getUserId(), userInfo.getRealName(), service.getName(), service.getLogo(),
                OriginalPrice, service.getDesc(), mounth, 1, notifyUrl, "", service.getId() + "", "0", "1", "2", "", "", mService.getId() + "", null, (mCoupon != null ? mCoupon.getKeyCode() : null), (mCoupon != null ? mCoupon.getAmount() : 0));
        /*//测试在线报名支付
        PayDetail payDetail = PayHelper.getInstance().getPayDetail(userInfo.getUserId(),userInfo.getRealName(),"2016年央视\"希望之心\"英语风采大赛","",
                OriginalPrice,service.getDesc(),1,2,"","",service.getId()+"","0","1","2","(初赛)","比赛赛区：贵阳   比赛时长：120秒");*/

        startPay(payDetail);
    }

    /**
     * 拼接购买信息
     *
     * @param //服务售价信息      typeId类型为14、25 以月为单位，其它类型以年为单位。规定：typeId :25,只能是参数（6、12、36）
     * @param //versionType 1:个人版;2:班级版;3:校园版
     * @return 之前参数
     * //Service service,int versionType, int mounth
     */
    private List<String> concatBuyMsg(BuyMsg bugMsg) {
        //要按照字母的顺序进行排序  不然不成功
        List<String> s = new ArrayList<String>();
//        s.add("C=" + servicePriceInfo.getMonthcount());
        //改需求后固定为十年
        // s.add("C=" + mounth);
        // s.add("C=" + servicePriceInfo.getMonthcount());
        /*s.add("C=" + mounth);
        // s.add("N=" +servicePriceInfo.getName());
        s.add("N=" + service.getName());
        s.add("S=3");
        s.add("T=" + mService.getId());
        s.add("V=" + versionType);*/

        //增加在线报名之后 新的签名方式和参数

        //编码格式，固定为UTF-8。
        s.add("_input_charset=" + "utf-8");//1
        //标识客户端
        s.add("app_id=" + bugMsg.getApp_id());//2
        //标识客户端来源。参数值内容约定如下：1：WEB; 2:IOS; 3: Android
        s.add("appenv=" + bugMsg.getAppenv());//3
        //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        s.add("body=" + bugMsg.getBody());//4

        //服务类型： 月份数量或购买个数；
        /*goods_number  类型为14、25 ,27以月为单位，其它类型以年为单位,
                规定：goods_number  :25,只能是参数（6、12、36）;
        产品类型：为购买的数量。
        其它类型： 默认为1。*/
        s.add("goods_num=" + bugMsg.getGoods_num());//5

        //商品主键ID(25:阳光英语报服务)。
        s.add("goods_number=" + bugMsg.getGoods_number());//6

          /*具体区分商品类型。
        0:服务 ;1：书籍 ;
        9：其它（报名、投票...）。
        默认为0*/
        s.add("goods_type=" + bugMsg.getGoods_type());//7

        //具体区分商品版本1:个人版;2:班级版;3:校园版。
        s.add("goods_version=" + bugMsg.getGoods_version());//8

        //支付中心服务器主动通知商户网站里指定的页面http路径。
        s.add("notify_url=" + bugMsg.getNotify_url());//9
        //网站唯一订单号
        s.add("out_trade_no=" + bugMsg.getOut_trade_no());//10
        //1为书城购买，2为开通服务，3为开通考级，4为视频中心，999为其他分类(默认为999)。
        s.add("pay_source=" + bugMsg.getPay_source());//11
        //支付类型。默认值为：1（商品购买）
        s.add("payment_type=" + bugMsg.getPayment_type());//12
        //接口名称，固定值
        s.add("service=" + "create_direct_pay_by_user");//13
        //商品的标题/交易标题/订单标题/订单关键字等。该参数最长为128个汉字。
        s.add("subject=" + bugMsg.getSubject());//14
        //该笔订单的资金总额，单位为RMB-Yuan。取值范围为[0.01，100000000.00]，精确到小数点后两位。
        s.add("total_fee=" + MeUtil.radixPoint(Double.valueOf(bugMsg.getTotal_fee()), 2));//15
        return s;
    }

    /**
     * 拼接扣款URL
     * 习币 的通知地址    和支付宝通知地址不是一个
     *
     * @param receiveId   使用者ID,为多个人开能用逗号分开
     * @param typeId      服务类型ID eg:25-阳光英语等
     * @param versionType 1:个人版;2:班级版;3:校园版
     * @param //service   typeId类型为14、25 以月为单位，其它类型以年为单位。规定：typeId :25,只能是参数（6、12、36）
     * @return 开通VIP支付通知URL
     */
    private String concatOpenVIPPayNotifyUrl(String receiveId, int typeId,
                                             int versionType, float nowPrice, float OriginalPrice, int mounth) {
        Map<String, String> params = new TreeMap<String, String>(
                new Comparator<String>() {
                    @Override
                    public int compare(String lhs, String rhs) {
                        return lhs.compareToIgnoreCase(rhs);
                    }
                });
        //这里做了改动 验证是否习币只能传整形////////////////////////////////
        int nowPrice1 = (int) nowPrice;
        int OriginalPrice1 = (int) OriginalPrice;
        //这里做了改动 验证是否习币只能传整形///////////////////////////////

        params.put("actualamount", nowPrice1 + "");
        // params.put("actualamount", servicePriceInfo.getPrice() + "");
//        params.put("num", servicePriceInfo.getMonthcount() + "");
        //改需求后固定为十年
        params.put("num", mounth + "");
        //params.put("num", servicePriceInfo.getMonthcount() + "");
        //保证签名的价格保留两位小数

        //String price = String.format("%.2f", servicePriceInfo.getOriginalPrice());
        // params.put("price",  servicePriceInfo.getOriginalPrice() + "");
        // params.put("price", price);
        //params.put("price", servicePriceInfo.getOriginalPrice() + "");
        //不保留两位小数因为有小数后习币购买不了

        params.put("price", OriginalPrice1 + "");
        params.put("receiveid", receiveId);
        // 购买来源（1：WEB;2:IOS;3: Android）
        params.put("source", "3");
        params.put("typeid", typeId + "");
        params.put("versiontype", versionType + "");
        params.put("_input_charset", "utf-8");
        params.put("userid", receiveId);
        params.put("sign", sign(params));
        params.put("payPassword", "%s");
        //这一个接口  习币是不支持小数的 只支持整形  习币通知地址
        return HttpHelper.concatUrl(params, MeAction.ACTION_IS_BUY_SERVICE
                + HttpHelper.getVerifyStr(HttpRequest.getVerifyInfo()));
    }

    /**
     * 支付签名
     *
     * @param params 需要签名的字段
     * @return 签名
     */
    private String sign(Map<String, String> params) {
        StringBuilder builder = new StringBuilder();
        Set<String> keys = params.keySet();
        int index = 0;
        for (String key : keys) {
            if (index != 0) {
                builder.append("&");
            }
            builder.append(key + "=" + params.get(key));
            index++;
        }
        builder.append(PAY_SING_KEY);
        params.remove("_input_charset");
        params.remove("userid");
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            CWLog.d("debug", builder.toString());
            messageDigest.update(builder.toString().getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        return toHexString(messageDigest.digest());
    }

    /**
     * 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式
     *
     * @param bytes 字节数组
     * @return 参数的十六进制（基数 16）无符号整数值的字符串表示形式
     */
    private String toHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                builder.append("0");
            }
            builder.append(hex);
        }
        CWLog.d("debug", builder.toString());
        return builder.toString();
    }

    /**
     * 开始支付
     *
     * @param payDetail
     */
    private void startPay(PayDetail payDetail) {
        Intent mIntent = new Intent(this, EMainActivity.class);
        mIntent.putExtra("PAY_DETAIL", payDetail);
        mIntent.putExtra("GO_BACK", R.string.go_back);
        startActivityForResult(mIntent, RequestCode.BuyServiceActivityResquestCode.REQ_CODE_PAY);
        setValideSource(true);
    }

    /**
     * 联系客服
     */
    private void contactService() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + getString(R.string.service_phone));
        intent.setData(data);
        intent.putExtra(BaseJumpManager.INTENT_FLAG_SOURCE, true);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        super.onDestroy();
    }


    @Override
    public void price(float nowPrice, float OriginalPrice, int mounth) {
        //动态改变价格回调
        this.nowPrice = nowPrice;
        this.OriginalPrice = nowPrice;
        this.mounth = mounth;
    }


    /**
     * 加载完成
     */
    private void loadOver() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isTheLastPageShow) {
                    service_refresh_view.onFooterRefreshComplete();
                    service_refresh_view.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                } else {
                    service_refresh_view.onFooterRefreshComplete();
                }
                if (bookPageCount == 1) {
                    sll_scroll.smoothScrollTo(0, 10);
                }
            }
        }, 350);
    }


    @Override
    public void OnPriceClick(Price price, Trial trial) {
        if (trial != null) {
            btn_buy_service.setText("免费体验");
            ll_coupon_text.setVisibility(View.GONE);
        } else if (price != null) {
            if (mService != null && mService.getBuyServiceType() == 1) {
                btn_buy_service.setText("通知家长购买");
            } else {
                btn_buy_service.setText("立即购买");
            }
            nowPrice = price.getPrice();
            OriginalPrice = price.getPrice();
            mounth = price.getUnit();
            if (mService.getCouponList() != null && mService.getCouponList().size() > 0) {
                ll_coupon_text.setVisibility(View.VISIBLE);
                setCouponPrice(nowPrice, mService.getCouponList());
            } else {
                java.text.DecimalFormat df = new java.text.DecimalFormat("#0");
                if (mService != null && mService.getBuyServiceType() == 1) {
                    btn_buy_service.setText("通知家长购买" + "(" + df.format(price.getPrice()) + "元）");
                } else {
                    btn_buy_service.setText("立即购买" + "(" + (df.format(price.getPrice())) + "元）");
                }
                ll_coupon_text.setVisibility(View.GONE);
            }
        }
    }


    //****************************************
    //书记详情页

    private void initViewPage(int salesType) {
        pageTitles = new ArrayList<String>();
        if (salesType == 1) {
            page_titles.setVisibility(View.GONE);
            ll_tab_text.setVisibility(View.VISIBLE);
            tv_tittle.setText("内容目录");
            pageTitles.add("内容目录");
            viewpager_catalog.setAdapter(new ViewPageTest(pageTitles, mDownLoadInfos));


        } else if (salesType == 0) {
            page_titles.setVisibility(View.GONE);
            ll_tab_text.setVisibility(View.VISIBLE);
            tv_tittle.setText("书籍列表");
            pageTitles.add("书籍列表");
            viewPageBookAdapter = new ViewPageBookAdapter(pageTitles, epaperInfos);
            viewpager_catalog.setAdapter(viewPageBookAdapter);

        }


    }

    @Override
    public void onPageSelected(int position) {


    }


    /**
     * 获取本地数据
     */
    private void getLocData() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CATALOGUE + mBookId, new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {

                        loadNetData();
                    }

                    @Override
                    public void failed(Object data) {

                        loadNetData();
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                //获取缓存数据
                                if (data instanceof CatelogBean) {
                                    catelogBean = (CatelogBean) data;
                                    if (catelogBean != null) {
                                        if (catelogBean != null) {
                                            mCatalogueInfos.clear();
                                            mCatalogueInfos = catelogBean.getCatalogues();
                                        }

                                        mDownLoadInfos = DownLoadDB.queryListByBookId("2744", CatalogueInfo.PackageMode.PACKAGE_MODE_OLD);

                                        if (mDownLoadInfos.size() == 0 || mDownLoadInfos == null) {
                                            //如果数据库没有数据得先添加到数据库
                                            Log.d("DownLoadInfos", "####mDownLoadInfos.size() == 0 || mDownLoadInfos == null#########");
                                            mDownLoadInfos = fillList(mCatalogueInfos);
                                        } else {
                                            Log.d("DownLoadInfos", "####mDownLoadInfos.size()#########" + mDownLoadInfos.size());
                                        }
                                        //  upData();
                                        initViewPage(salesType);
                                    } else {


                                    }
                                } else {


                                }
                            }
                            loadNetData();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }


    private void loadNetData() {
        EpaperDao.getInstance().getBookCatalogue(mBookId + "", "", null,
                new BaseExtCallBack(BuyServiceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                    @Override
                    public void success(final Object data) {
                        try {
                            //后台没数据临时用之前的接口
                            catelogBean = (CatelogBean) data;
                            if (catelogBean != null) {
                                mCatalogueInfos.clear();
                                mCatalogueInfos = catelogBean.getCatalogues();
                                mSubjectId = catelogBean.getPackages().getSubjectId();
                                mCurrentEpaperInfo = makeEpaperInor(catelogBean);
                            }
                            //缓存数据本地数据无网络也可以操作
                            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CATALOGUE + mBookId, catelogBean);

                            //先获取之前存的数据库信息已避免已经存在的数据库状态被清空
                            mDownLoadInfos = DownLoadDB.queryListByBookId(mBookId + "", CatalogueInfo.PackageMode.PACKAGE_MODE_OLD);
                            //如果数据库没有数据得先添加到数据库
                            mDownLoadInfos = fillList(mCatalogueInfos);
                            //upData();
                            initViewPage(salesType);
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        //网络获取失败了再走本地获取流程
                        super.failed(errorCode, data);
                        mesData = data;

                    }

                    @Override
                    public void failed(Object data) {
                        super.failed(data);
//                        getLocData();
                        mesData = data;
                    }
                });
    }

    /**
     * 解析从网络获取的章节信息并填充列表
     *
     * @param catalogueInfos
     */
    private List<DownLoadInfo> fillList(List<CatalogueInfo> catalogueInfos) {
        List<DownLoadInfo> downLoadInfos = new ArrayList<DownLoadInfo>();
        List<DownLoadInfo> tempList = new ArrayList<DownLoadInfo>();


        parseCatalogueList(downLoadInfos, catalogueInfos);


        out:
        for (DownLoadInfo info : downLoadInfos) {
            if (info == null) {
                continue;
            }

            // 一本书有可能新包就包混合，必须每个章节判断是否是新资源

            for (DownLoadInfo downLoadInfo : mDownLoadInfos) {
                // 书的章节结构没有变化的
                if (downLoadInfo != null && downLoadInfo.getChapterId() != null && downLoadInfo.getChapterId().equals(info.getChapterId()) && downLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD) {
                    downLoadInfo.setChapterName(info.getChapterName());
                    downLoadInfo.setUrl(info.getUrl());
                    downLoadInfo.setSavePath(info.getSavePath());
                    downLoadInfo.setSize(info.getSize());
                    tempList.add(downLoadInfo);
                    DownLoadDB.insertDetail(downLoadInfo);
                    continue out;
                }
            }

            if (info.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD) {
                // 新增章节插入
                DownLoadInfo newDownLoadInfo = new DownLoadInfo();
                newDownLoadInfo.setBookId(mBookId + "");
                newDownLoadInfo.setBookName(info.getBookName());
                newDownLoadInfo.setIconUrl(info.getIconUrl());
                newDownLoadInfo.setChapterId(info.getChapterId());
                newDownLoadInfo.setChapterName(info.getChapterName());
                newDownLoadInfo.setUrl(info.getUrl());
                newDownLoadInfo.setSavePath(info.getSavePath());
                newDownLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                newDownLoadInfo.setSize(info.getSize());
                newDownLoadInfo.setIsFree(info.getIsFree());
                //newDownLoadInfo.setIsKaoShi(mInfo.getRequired());
                newDownLoadInfo.setResourceName(info.getResourceName());
                newDownLoadInfo.setResourceType(info.getResourceType());
                tempList.add(newDownLoadInfo);
                CWLog.e("TAT", "newDownLoadInfo" + newDownLoadInfo.toString());
                DownLoadDB.insertDetail(newDownLoadInfo);
            }

        }


        return tempList;
    }


    /**
     * 从网络下载的数据catalogueInfos，递归获取小题和子题，放至downLoadInfos中
     *
     * @param downLoadInfos
     * @param catalogueInfos
     */
    private void parseCatalogueList(List<DownLoadInfo> downLoadInfos,
                                    List<CatalogueInfo> catalogueInfos) {

        DownLoadInfo downLoadInfo = null;
        for (CatalogueInfo catalogueInfo : catalogueInfos) {
            if (catalogueInfo != null) {
                String url = catalogueInfo.getDownLoadUrl();
                downLoadInfo = new DownLoadInfo();
                downLoadInfo.setUrl(url);
                downLoadInfo.setChapterId(catalogueInfo.getId());
                downLoadInfo.setChapterName(catalogueInfo.getName());
                downLoadInfo.setHash(catalogueInfo.getHash());
                downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(BuyServiceActivity.this, url));

                //新旧包结构区分
                downLoadInfo.setType(catalogueInfo.getType());

                String fileSize = catalogueInfo.getFileSize();
                if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                }
                downLoadInfo.setIsFree(catalogueInfo.getIsFree());
                downLoadInfos.add(downLoadInfo);
                if (catalogueInfo.getChildren() != null
                        && catalogueInfo.getChildren().size() != 0) {
                    parseCatalogueList(downLoadInfos,
                            catalogueInfo.getChildren());
                }
            }
        }
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        bookPageCount++;
        getServiceBooks(mSchoolId);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        service_refresh_view.onHeaderRefreshComplete();
    }


    private class ViewPageTest extends StaticPagerAdapter {

        private List<String> titleChar;
        private List<DownLoadInfo> downLoadInfo_lists;

        public ViewPageTest(List<String> tTitleChar, List<DownLoadInfo> downLoadInfo_lists) {
            if (tTitleChar == null) {
                tTitleChar = new ArrayList<String>();
            }
            this.titleChar = tTitleChar;
            this.downLoadInfo_lists = downLoadInfo_lists;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return this.titleChar.get(position);
        }

        @Override
        public int getCount() {
            return this.titleChar.size();
        }

        @Override
        public View getView(ViewGroup container, int position) {
            View mianView = mInflater.inflate(R.layout.catalog_page_buybook, null);
            try {
                final LayersView layersView = (LayersView) mianView.findViewById(R.id.layear_layout);
                View sortView = mianView.findViewById(R.id.scor_item);
                recyclerViewContent = mianView.findViewById(R.id.content_book);

                contentLayersView = layersView;
                ((TextView) mianView.findViewById(R.id.count_id)).setText("已更新" + catelogBean.getPublished() + "/共" + catelogBean.getPeriods());
                layersView.setForm(from);
                //layersView.setKaoShi(mInfo.getRequired());
                layersView.setmDownLoadInfoList(downLoadInfo_lists);
                // layersView.setBookchapters(bookchapters);
                layersView.setCatalogueInfos(mCatalogueInfos);


                sortView.setVisibility(View.VISIBLE);
                final ImageView sortImage = (ImageView) mianView.findViewById(R.id.sort_iocn);

                if (catelogBean.getIsdesc() == 1) {
                    //降序
                    sortImage.setImageResource(R.mipmap.sort_rev);
                    layersView.setSortState(true);
                } else {
                    //升序
                    sortImage.setImageResource(R.mipmap.sort_def);
                    layersView.setSortState(false);
                }

                mianView.findViewById(R.id.sco_lin).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (layersView.sort()) {
                            sortImage.setImageResource(R.mipmap.sort_rev);
                        } else {
                            sortImage.setImageResource(R.mipmap.sort_def);
                        }
                    }
                });

                /**
                 * 添加鉴权逻辑
                 */

                handleCatalogClick(layersView);

//                }
            } catch (Exception e) {
                e.getStackTrace();
            }

            return mianView;
        }

    }

    private void handleCatalogClick(LayersView layersView) {
        /**
         * 购买与不购买都是这个逻辑
         */
        layersView.bindLinearLayout();
        layersView.setOnItemClickListener(new LayersView.ItemClick() {


            @Override
            public void lastItemClick(Node node, View view) {
                //点击章节
                if (node.isSuo() && from != IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE) {
                    ToastUtil.INSTANCE.toastInCenter(BuyServiceActivity.this, "考试用书不支持自主学习哦~~");
                } else {
                    Hoder hoder = new Hoder();
                    hoder.imageView = (ImageView) view.findViewById(R.id.item_iocn);
                    executorDBThread(node.getCatalogueInfo(), hoder);
                }
            }

            @Override
            public boolean freeForLearnContralItemClick(int item, Node node, Node node0) {//现在是在node为最后一级条目情况下判断的

                if (node.getpId() == 0 && item != 0)  //对非第一个一级条目 父条目判断
                    return false;
                if (node.getpId() != 0 && node.getParent() != null) {//对第有子目录判断
                    if (node.getParent().getParent() != null) {//有三级目录
                        if (node.getParent().getpId() != node0.getId())
                            return false;
                    } else {//只有二级目录
                        if (node.getpId() != node0.getId())
                            return false;
                    }

                }
                // TODO: 2018/7/2 服务页 暂时去掉免费试用 此处为false则不可点击，true
//                return true;
                return false;

            }
        });

    }

    public static class Hoder extends CatalogNewActivity.Hoder {
        public ImageView imageView;
    }

    private class ViewPageBookAdapter extends StaticPagerAdapter {

        private List<String> titleChar;
        private List<EpaperInfo> epaperInfos;

        public ViewPageBookAdapter(List<String> tTitleChar, List<EpaperInfo> epaperInfos) {
            if (tTitleChar == null) {
                tTitleChar = new ArrayList<String>();
            }
            this.titleChar = tTitleChar;
            this.epaperInfos = epaperInfos;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return this.titleChar.get(position);
        }

        @Override
        public int getCount() {
            return this.titleChar.size();
        }

        public void setEpaperInfos(List<EpaperInfo> epaperInfos) {
            this.epaperInfos = epaperInfos;
            notifyDataSetChanged();
        }

        @Override
        public View getView(ViewGroup container, int position) {
            View mianView = mInflater.inflate(R.layout.book_page, null);
            try {
                ListViewForScrollView lv_book_list = mianView.findViewById(R.id.lv_book_list);
                RecyclerView content_book = mianView.findViewById(R.id.content_book_desc);

                servers_nums = mianView.findViewById(R.id.servers_nums);
                buyServiceSum = mianView.findViewById(R.id.buy_service_sum);
                /*if (position == 0) {
                    lv_book_list.setVisibility(View.GONE);
                    servers_nums.setVisibility(View.GONE);
                    content_book.setVisibility(View.VISIBLE);
                    content_book.setLayoutManager(new LinearLayoutManager(BuyServiceActivity.this));
                    bookContentAdapter = new BookContentAdapter(mService.getDesc(), mService.getPhotos(), BuyServiceActivity.this);
                    content_book.setAdapter(bookContentAdapter);

                } else {*/
                lv_book_list.setVisibility(View.VISIBLE);
                servers_nums.setVisibility(View.VISIBLE);
                content_book.setVisibility(View.GONE);
                addBookAdapter = new AddBookAdapter(BuyServiceActivity.this, AddBookAdapter.ADD_TYPE_ALL, epaperInfos, false);
                lv_book_list.setAdapter(addBookAdapter);
                buyServiceSum.setText("(共" + books_nums + "本)");


                lv_book_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        EpaperInfo epaperInfo = (EpaperInfo) parent.getItemAtPosition(position);
                        if (epaperInfo != null) {
                            EpaperJumpManager.jumpToCatalog(R.string.go_back, BuyServiceActivity.this, epaperInfo, IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs, -1, serviceId);
                        }
                    }
                });
//                }
            } catch (Exception e) {
                e.getStackTrace();
            }

            return mianView;
        }
    }

    private class BookContentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private String desc;
        private List<Photo> photos;
        private Context context;

        public BookContentAdapter() {

        }

        public BookContentAdapter(String desc, List<Photo> photos, Context context) {
            this.desc = desc;
            this.photos = photos;
            this.context = context;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view;
            try {
                if (viewType == 0) {
                    view = View.inflate(parent.getContext(), R.layout.desc, null);

                    return new DescViewHolder(view);
                } else {
                    view = View.inflate(parent.getContext(), R.layout.image, null);

                    return new ImageViewHolder(view);
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            try {
                if (position == 0) {
                    final DescViewHolder descViewHolder = (DescViewHolder) holder;
                    descViewHolder.descTv.setText(desc);

                } else {
                    final ImageViewHolder imageViewHolder = (ImageViewHolder) holder;
                    Glide.with(context).load(photos.get(position - 1).getUrl()).into(imageViewHolder.imageTv);
                }
            } catch (Exception e) {
                e.getStackTrace();
            }


        }

        @Override
        public int getItemCount() {
            if (photos != null) {
                return photos.size() + 1;
            } else {
                return 1;
            }

        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

    }

    static class DescViewHolder extends RecyclerView.ViewHolder {
        private TextView descTv;

        public DescViewHolder(View itemView) {
            super(itemView);
            descTv = itemView.findViewById(R.id.desc_tv);
        }
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageTv;

        public ImageViewHolder(View itemView) {
            super(itemView);
            imageTv = itemView.findViewById(R.id.image_book_tv);
        }
    }
/**
 * ===================================================
 */

    /**
     * 下面是服务中心 精品书籍做题逻辑
     */


    /**
     * 执行数据库线程操作  从数据库中获取下载对象
     */
    public void executorDBThread(final CatalogueInfo catalogueInfo, final Hoder hoder) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                final DownLoadInfo downLoadInfo = getLocalDownLoadInfoByDB(catalogueInfo);
                mCurrentClickDownloadInfo = downLoadInfo;

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        doClickListener(catalogueInfo, downLoadInfo, hoder, true);
                    }
                });

            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 生成epaper 信息
     */


    private EpaperInfo makeEpaperInor(CatelogBean catelogBean) {
        if (catelogBean == null) {
            return null;
        }
        if (catelogBean.getPackages() == null) return null;
        PackagesBean packages = catelogBean.getPackages();
        EpaperInfo epaperInfo = new EpaperInfo();
        epaperInfo.setPackageId(packages.getPackage_id() + "");
        epaperInfo.setProductId(packages.getPackage_id() + "");
        epaperInfo.setSubjectId(packages.getSubjectId());
        epaperInfo.setBookIntro(packages.getDescription());
        epaperInfo.setCover(packages.getCover());
        epaperInfo.setGrade(Integer.parseInt(packages.getGradeId()));
        epaperInfo.setProductName(packages.getBook_name());
//        epaperInfo.setPackageType(packages.getPackageType());
        epaperInfo.setPeriod(packages.getPeriodId());
        epaperInfo.setIsFree(packages.getPeriodId());

//        epaperInfo.setServer(qrAndBrandInfos.get(0));

        return epaperInfo;
    }

    /**
     * 获取数据库中DownLoadInfos
     *
     * @param curInfo
     */
    private DownLoadInfo getLocalDownLoadInfoByDB(CatalogueInfo curInfo) {
        List<DownLoadInfo> tempList = DownLoadDB.queryListByBookId(String.valueOf(mBookId), CatalogueInfo.PackageMode.PACKAGE_MODE_OLD);
        DownLoadInfo downLoadInfo = null;


        for (DownLoadInfo info : tempList) {
            if (info.getChapterId().equals(curInfo.getId())) {
                downLoadInfo = info;
            }
        }
        if (downLoadInfo != null) {
            return downLoadInfo;
        } else {
            return null;
        }

    }

    /**
     * item监听事件
     *
     * @param downLoadInfo
     */
    public void doClickListener(final CatalogueInfo catalogueInfo, final DownLoadInfo downLoadInfo, Hoder hoder, boolean isHandClick) {
        if (from == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE) {

            if (catalogueInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW)
//            if (catalogueInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD)
            {
                //新结构此处不需要下载
                EpaperJumpManager.jumpToContentNew(
                        R.string.go_back,
                        BuyServiceActivity.this, catalogueInfo, serviceId, mCurrentEpaperInfo, null,IntentValue.JumpToBookCatalogType.NORMAL);

            } else if (downLoadInfo != null) {
                if (TextUtils.isEmpty(downLoadInfo.getUrl())) {
                    showToastError(R.string.package_no_publish);
                    return;
                }
                downLoadInfoMap.put(downLoadInfo, hoder);
                switch (downLoadInfo.getStatus()) {
                    case DownloadStatus.STATUS_NORMAL:
                    case DownloadStatus.STATUS_FAILED:
                    case DownloadStatus.STATUS_FAILED_SDISFULL:
                    case DownloadStatus.STATUS_FAILED_UNZIP:
                        if (DialogUtil
                                .sdIsFullForDownload(BuyServiceActivity.this, downLoadInfo)) {
                            DialogUtil.showSdFullDialog(
                                    BuyServiceActivity.this,
                                    downLoadInfo.getSize());
                            return;
                        }
                        if (!NetworkUtils.isOnline()) {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                            return;
                        }
                        downLoadInfo.setHash(catalogueInfo.getHash());//只有下载的时候更新HASH值
                        judgeDownloadMetod(catalogueInfo, downLoadInfo, hoder);
                        break;
                    case DownloadStatus.STATUS_LOADING:
                        DownLoad.getInstance().pauseTask(downLoadInfo);
                        break;
                    case DownloadStatus.STATUS_DOWNLOADING:
                        DownLoad.getInstance()
                                .pauseTask(downLoadInfo);
                        break;
                    case DownloadStatus.STATUS_PAUSE:
                        if (!NetworkUtils.isOnline()) {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                            return;
                        }
                        showDownloadDialog(downLoadInfo, catalogueInfo, hoder);
                        DownLoad.getInstance()
                                .resumeTask(downLoadInfo);
                        break;
                    case DownloadStatus.STATUS_UPZIPING:
                        // DownLoad.getInstance().addTask(info);
                        break;
                    case DownloadStatus.STATUS_COMPLETED:
                        //判断是否需要更新离线包
                        if (downLoadInfo.getHash() == null || "".equals(downLoadInfo.getHash()) || !(downLoadInfo.getHash().equals(catalogueInfo.getHash()))) {//资源包有更新
                            reDownloadOrOnlyDeleteData(catalogueInfo, downLoadInfo, hoder, isHandClick);
                        } else {
                            String packageDir = ESystem
                                    .getPackagesMainJsonPath(
                                            downLoadInfo.getBookId(),
                                            downLoadInfo.getChapterId());

                            //新包拆分逻辑增加 资源 versionId,
                            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(downLoadInfo.getBookId(),
                                    downLoadInfo.getChapterId());
                            String resourcePath = ESystem.getPackagesResourcePath(downLoadInfo.getBookId(),
                                    downLoadInfo.getChapterId());
                            //服务权限判断，跳转资源详情页
                            if (new File(packageDir).exists() && new File(catalogueJsonPath).exists()
                                    && new File(resourcePath).exists()) {
                                //自动打开才去判断
                                if (!isHandClick) {
                                    if (!isDownloadInfoTheSame(downLoadInfo)) {
                                        return;
                                    }
                                }
                                EpaperJumpManager.jumpToContent(
                                        R.string.go_back,
                                        BuyServiceActivity.this,
                                        downLoadInfo, serviceId, mCurrentEpaperInfo, null);
                            } else {
                                reDownloadOrOnlyDeleteData(catalogueInfo, downLoadInfo, hoder, isHandClick);
                            }

                        }
                        break;
                }
            }


        } else {//来自资源中心点击了资源包，不允许下载和使用。

        }
    }

    private void reDownloadOrOnlyDeleteData(CatalogueInfo catalogueInfo, final DownLoadInfo downLoadInfo, Hoder hoder, boolean isHandClick) {
        String path = ESystem.getPackagesCatalogue(downLoadInfo.getBookId(), downLoadInfo.getChapterId());//资源包地址
        //删除本地文件
        FileUtils.delete(path);
        //重新下载
        downLoadInfo.setHash(catalogueInfo.getHash());//只有下载的时候更新HASH值
        downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
        downLoadInfo.setProgress(0);
        if (isHandClick) {
            downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
            judgeDownloadMetod(catalogueInfo, downLoadInfo, hoder);
        } else {
            ThreadTask.getInstance().executorDBThread(new Runnable() {
                public void run() {
                    DownLoadDB.insertDetail(downLoadInfo);
                }
            }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
            ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);

        }
    }

    private void judgeDownloadMetod(CatalogueInfo catalogueInfo, DownLoadInfo downLoadInfo, Hoder hoder) {
        if (NetworkUtils.isWifiOnline()) {
            showDownloadDialog(downLoadInfo, catalogueInfo, hoder);
            DownLoad.getInstance()
                    .addTask(downLoadInfo);
        } else {
            DialogUtil.showWIFIDialogOfCatalog(
                    BuyServiceActivity.this,
                    downLoadInfo, catalogueInfo, hoder);
        }
    }

    public void showDownloadDialog(DownLoadInfo downLoadInfo, CatalogueInfo catalogueInfo, Hoder hoder) {
        mCurrentCatalogueInfo = catalogueInfo;
        mCurrentHolder = hoder;
        showDownloadProgress();
        showCancelButtonOfDownloadProgress();
    }


    /**
     * 设置优惠券的价格
     *
     * @param price
     * @param couponList
     */
    public void setCouponPrice(float price, List<Coupon> couponList) {
        String buyBtnText = "";
        String payBtnText = "";
        if (price <= 0) {
            ll_coupon_text.setVisibility(View.GONE);
            return;
        }
        float amount = 0;
        for (int i = 0; i < couponList.size(); i++) {
            Coupon itme = couponList.get(i);
            if (itme.getBottomAmount() == price) {
                amount = itme.getAmount();
                this.mCoupon = itme;
                break;
            }
        }
        if (amount > 0) {
            tv_coupon_amount.setText("-¥" + amount);
            tv_total_amount.setText("¥" + (price - amount));
            tv_coupon_end_date.setText(mCoupon.getEndDate() + "过期");
            if (null != btn_buy_service.getText() && !"".equals(btn_buy_service.getText())) {
                buyBtnText = btn_buy_service.getText().toString();
                if (buyBtnText.equals("通知家长购买") || buyBtnText.equals("立即购买")) {
                    float v = price - amount;
                    payBtnText = buyBtnText + "(" + v + "元" + ")";
                    btn_buy_service.setText(payBtnText);
                }
            }
        } else {
            this.mCoupon = null;
            tv_coupon_amount.setText("暂无可用");
            ll_coupon_text.setVisibility(View.GONE);
            buyBtnText = btn_buy_service.getText().toString();
            buyBtnText = buyBtnText + "(" + price + "元" + ")";
            btn_buy_service.setText(buyBtnText);
        }
    }

    private boolean isDownloadInfoTheSame(DownLoadInfo downLoadInfo) {
        return downLoadInfo.getBookId().equals(mCurrentClickDownloadInfo.getBookId()) &&
                downLoadInfo.getChapterId().equals(mCurrentClickDownloadInfo.getChapterId()) &&
                downLoadInfo.getModuleId().equals(mCurrentClickDownloadInfo.getModuleId() + "") &&
                downLoadInfo.getVersionId().equals(mCurrentClickDownloadInfo.getVersionId());
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        DownLoadInfo info = item.getInfo();
        Hoder hoder = findHoder(info);
        mCurrentDownloadInfo = info;
        mCurrentHolder = hoder;
        dealCircleProgress(info, hoder);
    }

    private Hoder findHoder(DownLoadInfo info) {
        for (DownLoadInfo key : downLoadInfoMap.keySet()) {
            if (key.getChapterId().equals(info.getChapterId()) && key.getChapterName().equals(info.getChapterName())) {
                debug("----------keykey-------------" + key.getChapterId() + "-----固定的info------" + info.getChapterId() + "---------name--" + key.getChapterName() + "----" + info.getChapterName());
                return downLoadInfoMap.get(key);
            }
        }
        return null;
    }

    private void debug(String message) {
        Log.d(this.getClass().getName(), message);
    }

    private void dealCircleProgress(final DownLoadInfo downLoadInfo, Hoder hoder) {
        if (hoder == null)
            return;

        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_FILE_DOWNLOAD:
                hideCancelButtonOfDownloadProgress();
                break;
            case DownloadStatus.STATUS_COMPLETED:
                hideDownloadProgress();
                String packageDir = ESystem.getPackagesCatalogue(
                        mCurrentDownloadInfo.getBookId(), mCurrentDownloadInfo.getChapterId());
                //判断解压后文件是否存在，不存在的话直接给出加载失败提示
                if (new File(packageDir).exists()) {
                    if (mCurrentCatalogueInfo != null && mCurrentHolder != null) {
                        doClickListener(mCurrentCatalogueInfo, mCurrentDownloadInfo, mCurrentHolder, false);
                    }
                } else {
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                }

                break;
            case DownloadStatus.STATUS_FAILED:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_SDISFULL:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_UNZIP:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                break;
        }
    }
}
